/**
 * 粉丝相关
 * @authors 杨兴洲（of2502）
 * @date    2017/3/13 10:25
 * @version 1.0
 */

import {Router} from "express";
import UserService from "../../service/user-service";
import WxUserService from "../../service/weixin-user-service";

const router = Router();

function checkOpenidList(req, res, next) {
    let {openid_list} = req.body || req.query;
    if (!Array.isArray(openid_list)) {
        const error = new Error();
        error["errcode"] = 10002;
        error["errmsg"] = "openid_list必须是数组类型";
        return next(error);
    }

    next();
}

/**
 * 获取公众号粉丝列表
 */
router.get('/list', (req, res, next) => {
    (async () => {
        try {
            const {pageSize, next_openid, tagID} = req.query;
            const {userID} = res.locals;
            const access_token = await UserService.getAccessToken(userID);
            const result = tagID ?
                await WxUserService.getListByTag({access_token, tagID, next_openid}) :
                await WxUserService.getList({access_token, next_openid});
            // 无列表
            if (result.count === 0) {
                result.list = [];
                return res.status(200).json(result);
            }
            // 正常情况
            const list = result.data ? result.data.openid : [];
            const count = Math.min(+pageSize, list.length);
            res.status(200).json({
                total: result.total,
                count,
                list: list.slice(0, count),
                next_openid: result.data.openid[count - 1]
            });

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取公众号粉丝详情
 */
router.post('/detail', checkOpenidList, (req, res, next) => {
    (async () => {
        try {
            let {openid_list} = req.body;
            const {userID} = res.locals;
            if (openid_list.length === 0) return res.status(200).json([]);
            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.batchGetUserInfo({access_token, openid_list});
            res.status(200).json(result.user_info_list || result);

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取用户身上的标签列表
 */
router.get('/tags', (req, res, next) => {
    (async () => {
        try {
            let {openid} = req.query;
            const {userID} = res.locals;
            if (!openid) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "openid不存在";
                return next(error);
            }

            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.getUserTags({access_token, openid});
            res.status(200).json(result);

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 设置用户备注名
 */
router.post('/remark/update', (req, res, next) => {
    (async () => {
        try {
            let {openid, remark} = req.body;
            const {userID} = res.locals;
            if (!openid || !remark) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "openid或者remark不存在";
                return next(error);
            }

            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.updateRemark({access_token, openid, remark});
            res.status(200).json(result);

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 批量为用户打标签
 */
router.post('/tagging', checkOpenidList, (req, res, next) => {
    (async () => {
        try {
            let {openid_list, tagID} = req.body;
            const {userID} = res.locals;
            if (!tagID) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "tagID参数不能为空";
                return next(error);
            }
            if (openid_list.length === 0) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "openid_list参数不能为空";
                return next(error);
            }

            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.batchTagging({access_token, openid_list, tagID});
            res.status(200).json(result);

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 批量为用户取消标签
 */
router.post('/untagging', checkOpenidList, (req, res, next) => {
    (async () => {
        try {
            let {openid_list, tagID} = req.body;
            const {userID} = res.locals;
            if (!tagID) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "tagID参数不能为空";
                return next(error);
            }
            if (openid_list.length === 0) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "openid_list参数不能为空";
                return next(error);
            }

            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.batchUntagging({access_token, openid_list, tagID});
            res.status(200).json(result);

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取黑名单列表
 */
router.get('/block/list', (req, res, next) => {
    (async () => {
        try {
            const {begin_openid, pageSize=10000} = req.query;
            const {userID} = res.locals;
            const access_token = await UserService.getAccessToken(userID);
            const result = await WxUserService.getBlacklist({access_token, begin_openid});

            // 无列表
            if (result.count === 0) {
                result.list = [];
                return res.status(200).json(result);
            }
            // 正常情况
            const list = result.data ? result.data.openid : [];
            const count = Math.min(+pageSize, list.length);
            res.status(200).json({
                total: result.total,
                count,
                list: list.slice(0, count),
                next_openid: result.data.openid[count - 1]
            });

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 批量黑名单
 */
router.post('/block', checkOpenidList, (req, res, next) => {
    (async () => {
        try {
            let {openid_list} = req.body;
            const {userID} = res.locals;
            if (openid_list.length === 0) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "openid_list参数不能为空";
                return next(error);
            }

            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.batchBlacklist({access_token, openid_list});
            res.status(200).json(result);

        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 批量取消黑名单
 */
router.post('/unblock', checkOpenidList, (req, res, next) => {
    (async () => {
        try {
            let {openid_list} = req.body;
            const {userID} = res.locals;
            if (openid_list.length === 0) {
                const error = new Error();
                error["errcode"] = 10001;
                error["errmsg"] = "openid_list参数不能为空";
                return next(error);
            }

            let access_token = await UserService.getAccessToken(userID);
            let result: any = await WxUserService.batchUnblacklist({access_token, openid_list});
            res.status(200).json(result);

        } catch (error) {
            next(error);
        }
    })();
});


export default router;
